package org.iartisan.thought.server.service.management;

import org.iartisan.runtime.constants.DataStatus;
import org.iartisan.runtime.constants.FlagType;
import org.iartisan.runtime.exception.NotAllowedException;
import org.iartisan.runtime.support.BaseManagementServiceSupport;
import org.iartisan.runtime.utils.BeanUtil;
import org.iartisan.runtime.utils.StringUtils;
import org.iartisan.runtime.utils.UUIDUtil;
import org.iartisan.thought.server.dbm.mapper.CommentMapper;
import org.iartisan.thought.server.dbm.model.CommentDO;
import org.iartisan.thought.server.service.bo.CommentBO;
import org.iartisan.thought.server.service.support.MessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


/**
 * <p>
 * cust query service
 *
 * @author King
 * @since 2017/12/15
 */
@Service
public class CommentManagementService extends BaseManagementServiceSupport<CommentMapper, CommentBO> {

    @Autowired
    private TopicManagementService topicManagementService;

    @Autowired
    private CommentZanRelationManagementService commentZanRelationManagementService;

    @Autowired
    private MessageHandler messageHandler;


    @Transactional
    public void saveData(CommentBO commentBO) {
        CommentDO dbInsert = BeanUtil.copyBean(commentBO, CommentDO.class);
        String commentId = UUIDUtil.shortId();
        dbInsert.setId(commentId);
        dbInsert.setStatus(DataStatus.E.toString());
        dbInsert.setIsAccept(FlagType.N.toString());
        dbInsert.setCreateTime(new Date());
        baseMapper.insert(dbInsert);
        //回复条数+1
        topicManagementService.addCommentCount(commentBO.getTopicId(), 1);
        if (StringUtils.isEmpty(commentBO.getReplyName())) {
            messageHandler.sendCommentMsg(commentBO.getTopicId(), commentId, commentBO.getCustomerId());
        } else {
            messageHandler.sendReplyMsg(commentBO.getTopicId(), commentId, commentBO.getCustomerId(), commentBO.getReplyName());
        }
    }

    public void accept(String commentId) {
        CommentDO dbResult = baseMapper.selectById(commentId);
        //更新 accept
        dbResult.setIsAccept(FlagType.Y.toString());
        dbResult.setUpdateTime(new Date());
        baseMapper.updateById(dbResult);
        //设置贴子为已结
        topicManagementService.setTopicEnd(dbResult.getTopicId());
    }

    @Transactional
    public void addZan(String commentId, String custId) throws NotAllowedException {
        commentZanRelationManagementService.addZanRelation(commentId, custId);
        //赞数+1
        CommentDO dbResult = baseMapper.selectById(commentId);
        dbResult.setZanCount((dbResult.getZanCount() == null ? 0 : dbResult.getZanCount()) + 1);
        dbResult.setUpdateTime(new Date());
        baseMapper.updateById(dbResult);
    }

}
